package com.example.spider.proxy.core.tester;

import com.example.spider.proxy.core.ProxyInfo;
import com.example.spider.proxy.core.ProxyTester;

/**
 * 代理有效性测试
 */
public class FillInfoProxyTester implements ProxyTester {

    /**
     * 测匿名度
     */
    private final TestCallBack locationCallBack;

    public FillInfoProxyTester(TestCallBack locationCallBack) {this.locationCallBack = locationCallBack;}

    @Override
    public boolean test(ProxyInfo proxyInfo) {
        ProxyTypeEnum oldProxyTypeEnum = proxyInfo.getProxyTypeEnum();
        proxyInfo.setProxyTypeEnum(ProxyTypeEnum.SOCKS4);
        ProxyInfo historyInfo = copyHistoryInfo(proxyInfo);

        boolean socksTestResult = ProxyTesterUtil.testProxyInfo(proxyInfo, locationCallBack);
        if (socksTestResult) {
            return true;
        }

        setHistory(historyInfo, proxyInfo);
        proxyInfo.setProxyTypeEnum(ProxyTypeEnum.HTTPS);
        boolean httpsTestResult = ProxyTesterUtil.testProxyInfo(proxyInfo, locationCallBack);
        if (httpsTestResult) {
            return true;
        }

        setHistory(historyInfo, proxyInfo);
        proxyInfo.setProxyTypeEnum(ProxyTypeEnum.HTTP);
        boolean httpTestResult = ProxyTesterUtil.testProxyInfo(proxyInfo, locationCallBack);
        if(!httpTestResult) {
            proxyInfo.setProxyTypeEnum(oldProxyTypeEnum);
        }
        return httpTestResult;
    }

    private ProxyInfo copyHistoryInfo(ProxyInfo proxyInfo) {
        ProxyInfo historyInfo = new ProxyInfo();
        setHistory(proxyInfo, historyInfo);
        return historyInfo;
    }

    private void setHistory(ProxyInfo historyInfo, ProxyInfo proxyInfo) {
        historyInfo.setLastVerificationTime(proxyInfo.getLastVerificationTime());
        historyInfo.setResponseTime(proxyInfo.getResponseTime());
        historyInfo.setTotalCount(proxyInfo.getTotalCount());
        historyInfo.setSuccessCount(proxyInfo.getSuccessCount());
        historyInfo.setSuccessPercentage(proxyInfo.getSuccessPercentage());
        historyInfo.setSuccessContinuityCount(proxyInfo.getSuccessContinuityCount());
        historyInfo.setFailCount(proxyInfo.getFailCount());
        historyInfo.setFailContinuityCount(proxyInfo.getFailContinuityCount());
        historyInfo.setScore(proxyInfo.getScore());
    }

}
